<template>
  <div class="specialParameter flowCloumn h100">
    <div class="topBtnDiv" v-if="showType != 'query'">
      <el-radio-group v-model="formSwitch" size="mini" @change="getTableData">
        <el-radio-button :label="true" title="统计模式">
          <i class="el-icon-s-data"></i>
        </el-radio-button>
        <el-radio-button :label="false" title="列表模式">
          <i class="el-icon-s-grid"></i>
        </el-radio-button>
      </el-radio-group>
    </div>
    <div class="constentmain h100">
      <div class="chartContent h100" v-if="formSwitch">
        <parameterStatistical />
      </div>
      <div class="tableContent" v-else>
        <listTableNew v-bind="tableSetting" ref="klTable"></listTableNew>
      </div>
    </div>
    <input
      type="file"
      ref="uploadFile"
      style="display: none"
      accept=".xls,.xlsx"
      :multiple="false"
      @change="autoUploadFile"
    />
  </div>
</template>
<script>
import {
  getListApi, //列表
  importApi
} from "@/api/specialManagement/specialParameter";

import parameterStatistical from "./parameterStatistical";
export default {
  components: { parameterStatistical },
  props: {
    //设备台账当前设备
    currentNode: {
      type: Object,
      default: () => {
        return {};
      },
    },
    showType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      show: false,
      path: "",
      uploadUrl: `${process.env.VUE_APP_BASEURL}/eam-service-standard/patrol/import`,
      pageType: "list",
      formSwitch: false,
      formData: {},
      currentDevice: {},
      statusColor: {
        normal: "#00B050",
        lag: "#FF3300",
      },
      tableSetting: {
        // selectionShow: true,
        showCustomBtn: true,
        showFilterBtn: true,
        pageConfig: {
          pageCode: "specialParameter", //页面标识，用来存储过滤器以及自定义列的时候用
          userId: this.$store.getters.userInfo.id,
        },
        searchObj: {
          searchMethod: (params, sortStr) => {
            this.getTableData(params, sortStr);
          },
          queryData: {
            page: 1,
            pageSize: 15,
            type: "",
          },
          searchArr: [
            {
              type: "input",
              label: "项目名称",
              model: "name",
            },
            {
              type: "input",
              label: "项目编号",
              model: "code",
            },
            {
              type: "dept", //user\organization
              label: "主办部门",
              model: "hostDeptName",
              idsStr: "hostDeptId",
              placeholder: "请选择主办部门",
              methods: (val) => {},
            },
            {
              type: "userOnly",
              label: "负责人",
              model: "leaderName",
            },
            // TODO
            {
              label: "所属年份",
              model: "belongYear",
              type: "year",
            },
            {
              type: "select",
              label: "重要等级",
              model: "importantLevel",
              option: this.$store.getters["dirtData"]("important_level"),
            },
            {
              type: "select",
              label: "当前状态",
              model: "milestoneStatus",
              option: this.$store.getters["dirtData"]("sp_progress_status"),
            },
            // {
            //   label: "项目状态",
            //   model: "status",
            //   type: "select",
            //   multiple: true,
            //   option: this.$store.getters["dirtData"]("sp_project_status"),
            // },
            {
              label: "项目类别",
              model: "projectType",
              type: "select",
              multiple: true,
              option: this.$store.getters["dirtData"]("sp_project_category"),
            },
            {
              label: "计划结束时间",
              model: "planFinishTime",
              type: "datetimerange",
            },
            {
              label: "创建时间",
              model: "createTime",
              type: "datetimerange",
            },
          ],
        },
        actionList: [
          {
            name: "新建",
            icon: "el-icon-plus",
            disabled: !this.$store.getters["isBtnAuth"]("add"),
            content: "未授权功能! ",
            method: (row) => {
              this.toAdd();
            },
          },
          {
            name: "导入",
            icon: "icon-daoru",
            disabled: !this.$store.getters.isBtnAuth("import"), //控制按钮的禁用
            isHide: false,
            content: "未授权此功能！",
            method: (row) => {
              this.uploadFile();
            },
          },
          {
            name: "下载模板",
            icon: "icon-xiazai",
            disabled: !this.$store.getters.isBtnAuth("download"), //控制按钮的禁用
            isHide: false,
            content: "未授权此功能！",
            method: (row) => {
              this.download();
            },
          },
        ],
        column: [
          {
            label: "项目编号",
            prop: "code",
            sortable: "custom",
            width: "240px",
          },
          {
            label: "项目名称",
            prop: "name",
            sortable: "custom",
            showTooltip: true,
            width: "270px",
          },
          {
            label: "主办部门",
            prop: "hostDeptName",
            sortable: "custom",
            width: "120px",
          },
          {
            label: "业务类别",
            prop: "bizCategory",
            scopeType: "formate",
            method: (row) => {
              return this.$store.getters["fineDirtDataName"](
                "biz_category",
                row.bizCategory
              );
            },
            sortable: "custom",
            width: "120px",
          },
          {
            label: "重要等级",
            prop: "importantLevel",
            scopeType: "formate",
            method: (row) => {
              return this.$store.getters["fineDirtDataName"](
                "important_level",
                row.importantLevel
              );
            },
            sortable: "custom",
            width: "120px",
          },
          {
            label: "项目类别",
            prop: "projectType",
            scopeType: "formate",
            method: (row) => {
              return this.$store.getters["fineDirtDataName"](
                "sp_project_category",
                row.projectType
              );
            },
            sortable: "custom",
            width: "120px",
          },
          // {
          //   label: "项目状态",
          //   prop: "acceptCriteria",
          //   scopeType: "formate",
          //   method: (row) => {
          //     let str =["normal","lag"].includes(row.acceptCriteria)? this.$store.getters.fineDirtDataName(
          //       "sp_progress_status",
          //       row.acceptCriteria
          //     ):"正常";
          //     let color = row.acceptCriteria=="lag"?"#FF3300":"#00B050";
          //     let dom = `<span style="color:${color}">${str}</span>`;
          //     return dom;
          //   },
          //   sortable: "custom",
          //   width: "110px",
          // },
          {
            label: "当前状态",
            prop: "milestoneStatus",
            scopeType: "formate",
            method: (row) => {
              const arr = this.$store.getters["dirtData"]("sp_progress_status")
              const status = row.milestoneStatus
              const labelObj = arr.find(item => item.value === status)
              if(status && labelObj) {
                const label = labelObj.label
                const colorByStatusMap = {
                  'NORMAL': '#00B050',
                  'FINISH': '#faa224',
                  'LAG': '#FF3300',
                }
                return `<div style="color: ${colorByStatusMap[status]}">${label}</div>`
              } else {
                return `<div>-</div>`
              }
            },
            sortable: "custom",
            width: "120px",
          },
          {
            label: "当前里程碑",
            prop: "currMilestone",
            sortable: "custom",
            formatter: (row) => {
              if(row.currMilestone === '0') return '未开始'
              if(row.currMilestone === null) return '已结束'
              return row.currMilestone
            },
          },
          {
            label: "负责人",
            prop: "leaderName",
            sortable: "custom",
            width: "110px",
          },
          {
            label: "总体进度",
            prop: "progress",
            sortable: "custom",
            formatter: (row) => {
              return row.progress + "%";
            },
            width: "110px",
          },
          {
            label: "计划结束时间",
            prop: "predictFinishTime",
            sortable: "custom",
            width: "140px",
          },
          {
            label: "创建时间",
            prop: "createTime",
            sortable: "custom",
            width: "140px",
          },
        ],
        //表格方法
        tableMethods: {
          //点击行的方法
          rowClick: (val) => {
            this.gotoDetails(val);
          },
        },
      },
    };
  },
  watch: {
    currentNode: {
      handler: function(newVal, oldVal) {
        this.currentDevice = Object.assign({}, newVal);
        let queryData = Object.assign(this.tableSetting.searchObj.queryData, {
          equipmentId: newVal.id,
          equipmentName: newVal.name,
        });
        this.tableSetting.searchObj.queryData = {};
        this.tableSetting.searchObj.queryData = queryData;
        setTimeout(() => {
          if (oldVal) {
            //不是第一次
            this.updateData();
          }
        }, 0);
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {},
  created() {
    /* 添加监听事件 */
    window.addEventListener("storage", this.updateData);
  },
  beforeDestroy() {
    /* 删除监听事件 */
    window.removeEventListener("storage", this.updateData);
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.pageType = "edit";
      if (this.showType == "query") {
        this.tableSetting.selectionShow = false;
        this.tableSetting.showCustomBtn = false;
        this.tableSetting.showFilterBtn = false;
        this.tableSetting.actionList = [];
      } else {
        this.$refs.klTable.getTableConfig(); //需要显示过滤器以及自定义列时要提前调用,不需要过滤器时不调用
      }
      setTimeout(() => {
        this.$refs.klTable.searchData();
      }, 1000);
    },
    updateData() {
      this.$refs.klTable.searchData(false,false);
    },
    getTableData(params, sortStr) {
      let form = { ...params };
      if (sortStr) {
        form.orders = sortStr;
      }
      getListApi(form)
        .then((res) => {
          let data = res.data.list || [];
          data.forEach(item => {
            return item.currentNode = item.milestone[0] && item.milestone[0].status || '-'
          })
          let total = res.data.total || 0;
          this.$set(this.tableSetting, "tableData", data);
          this.$set(this.tableSetting, "totalNumber", total);
        })
        .catch((e) => {
          this.$set(this.tableSetting, "tableData", []);
          this.$set(this.tableSetting, "totalNumber", 0);
        });
    },
    //新建
    toAdd() {
      this.pageType = "add";
      this.gotoDetails();
    },
    //打开详情页
    gotoDetails(data) {
      if (data) {
        this.pageType = "detail";
      }
      let form = {
        pageType: this.pageType,
      };
      if (this.pageType != "add") {
        form.id = data.id;
        // form.status = data.status;
        // form.progress = data.progress;
      }
      let { href } = this.$router.resolve({
        path: "/specialManagement/specialParameter/details",
        query: form,
      });
      window.open(href, "_blank");
    },
    //点击选择文件
    uploadFile() {
      const fileObj = this.$refs.uploadFile;
      fileObj.click();
    },
    //上传选择的文件
    async autoUploadFile(e, file) {
      try {
        let experimentFile = this.$refs.uploadFile.files[0];
      if (experimentFile.leng == 0) {
        return;
      } else {
        const formData = new FormData();
        formData.append("file", experimentFile);
        await importApi(formData);
        this.$refs.uploadFile.value = null;
        this.$message.success("导入成功");
        this.updateData();
      }
      } catch (error) {
      }
      
    },
    download() {
      let path = "eam-service-sinoprobe/sp/project/template";
      let fileName = "专项台账导入模板";
      this.$utils.downloadFile(null, fileName, path);
    },
  },
};
</script>
<style lang="less" scoped>
.specialParameter {
  position: relative;
  .topBtnDiv {
    position: absolute;
    text-align: right;
    right: 15px;
    top: 10px;
    z-index: 99;
  }
  .tableContent {
    padding: 20px;
    height: calc(100% - 40px);
  }
  .chartContent {
    background-color: @kr-main-bgcolor;
  }
}
</style>
